from django.template import loader, Context
from django import template
from urllib import quote
from os import path

from duetopia.opensearch.views import get_display_labels, get_display_fields

register = template.Library()

class OpenSearchTag(template.Node):
	@classmethod
	def parse_tag(cls, parser, token):
		return cls(*token.split_contents())

class Formats(OpenSearchTag):
	def __init__(self, tag, page_name):
		self.page_name = page_name
	def render(self, context):
		page = context[self.page_name]
		links = []
		for url in page.model._meta.search.templates:
			desc = url.get("description", url["type"])
			base, qs = url["template"].split("?", 1)
			target = base + "?page=%s" % page.number
			if context["query"]:
				target = target + "&" + context["query"]
			links.append((target, desc))
		t = loader.get_template("opensearch/result_formats.html")
		c = Context({"links" : links})
		return t.render(c)
register.tag("opensearch_formats", Formats.parse_tag)
	
class Results(OpenSearchTag):
	def __init__(self, tag, page_name):
		self.page_name = page_name
	def render(self, context):
		page = context[self.page_name]
		
		t = loader.get_template("opensearch/result_header.html")
		c = Context({"row_labels" : get_display_labels(page.model)})
		rows = [t.render(c)]
		
		t = loader.get_template("opensearch/result_row.html")
		for obj in page.object_list:
			row_id = "%s_%s_%s" % (obj._meta.app_label,
					       obj._meta.module_name,
					       obj.pk)
			c = Context({ "row_id" : row_id,
				      "row_data" : get_display_fields(obj) })
			rows.append(t.render(c))
			
		t = loader.get_template("opensearch/result_table.html")
		c = Context({"query": context["query"],
			     "page" : page,
			     "rows" : rows})
		return t.render(c)

register.tag("opensearch_results", Results.parse_tag)

class Map(OpenSearchTag):
	def __init__(self, tag, page_name):
		self.page_name = page_name
	def render(self, context):
		page = context[self.page_name]
		t = loader.get_template("opensearch/result_map.html")
		c = Context({})
		return t.render(c)
	
register.tag("opensearch_results_map", Map.parse_tag)
